package cc.rengu.igas.channel.wechat.core.service.trans;

import cc.rengu.igas.channel.wechat.common.constant.WechatConfigConstant;
import cc.rengu.igas.channel.wechat.common.constant.WechatTreeNodeConstant;
import cc.rengu.igas.channel.wechat.common.enums.RespCodeEnum;
import cc.rengu.igas.channel.wechat.core.model.ChnlBizResponse;
import cc.rengu.igas.channel.wechat.core.service.base.AuthService;
import cc.rengu.igas.channel.wechat.facade.request.WechatGetAuthCodeRequest;
import cc.rengu.igas.channel.wechat.facade.response.WechatGetAuthCodeResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.DstChannelCfg;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 获取用户授权
 */
public class WechatGetAuthCodeService extends AuthService {
    @Override
    protected Object beforeBizProcess() throws Exception {
        WechatGetAuthCodeRequest getAuthCodeRequest = new WechatGetAuthCodeRequest();
        ConvertUtil.convertOutput(getAuthCodeRequest);
        rglog.debug("state = <{}>", getAuthCodeRequest.getState());
        return getAuthCodeRequest;
    }

    @Override
    protected ChnlBizResponse callBizService(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        rglog.debug("tree=<{}>", xmlTreeUtil.toString());
        int iReturnCode = 0;
        WechatGetAuthCodeResponse getAuthCodeResponse = new WechatGetAuthCodeResponse();
        WechatGetAuthCodeRequest getAuthCodeRequest = (WechatGetAuthCodeRequest) request;
        DstChannelCfg dstChannelCfg = (DstChannelCfg) xmlTreeUtil.getXmlTreeObjectValue(WechatTreeNodeConstant.DST_CHANNEL_CFG, DstChannelCfg.class);

        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.TXN_NUM, getAuthCodeRequest.getHeader().getTxnNum());
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", dstChannelCfg.getSubAppId());
        paramMap.put("redirect_uri", URLEncoder.encode(getAuthCodeRequest.getRedirectUrl(), "UTF-8"));
        paramMap.put("response_type", "code");
        paramMap.put("scope", "snsapi_base");
        paramMap.put("state", getAuthCodeRequest.getState());
        rglog.debug("state=<{}>", getAuthCodeRequest.getState());
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(AppParamConstant.DEFAULT_INSTID,
                WechatConfigConstant.WECHAT_CONF_NODE, WechatConfigConstant.WECHAT_AUTH_URL);
        if (sysParam == null) {
            throw new BizException(RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespCode(), RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespDesc());
        }
        String requestUrl = generateHttpUrl(sysParam.getParamValue(), paramMap);
        rglog.debug("authUrl = <{}>", requestUrl);
        getAuthCodeResponse.setAuthUrl(requestUrl);
//       xmlTreeUtil.setXmlTreeStringValue(WechatTreeNodeConstant.DEFINE_HTTP_URL_NODE,requestUrl);
//        Schedule schedule = new Schedule();
//        iReturnCode = schedule.callService(WechatServiceConstant.WECHAT_PUBLIC_CLIENT_SERVICE,HttpMethod.GET);
//        if (0 != iReturnCode ){
//            rglog.error("调用支付宝服务失败，iReturnCode:<{}>",iReturnCode);
//            throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(),RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
//        }
        getAuthCodeResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        getAuthCodeResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        ChnlBizResponse chnlBizResponse = new ChnlBizResponse();
        chnlBizResponse.setResult(getAuthCodeResponse);
        return chnlBizResponse;
    }

    @Override
    protected void afterBizProcess(ChnlBizResponse response) throws Exception {
        WechatGetAuthCodeResponse getAuthCodeResponse = (WechatGetAuthCodeResponse) response.getResult();
        ConvertUtil.convertInput(getAuthCodeResponse);
    }

    /**
     * 根据配置拼装URL地址
     *
     * @param transUrl    URL地址
     * @param urlParamMap URL参数集合
     * @return URL地址
     */
    private String generateHttpUrl(String transUrl, Map<String, String> urlParamMap) {
        String requestUrlParam = "";
        Iterator<String> it = urlParamMap.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            requestUrlParam += key + "=" + urlParamMap.get(key) + "&";
        }
        return transUrl + requestUrlParam.substring(0, requestUrlParam.length() - 1) + "#wechat_redirect";
    }
}
